const $ = {
    storage: {
        set(key, value, expires = null) {
            try {
                const data = {
                    value,
                    timestamp: Date.now(),
                    expires: expires ? Date.now() + expires : null
                };
                localStorage.setItem(key, JSON.stringify(data));
                return true;
            } catch (error) {
                console.error('localStorage set error:', error);
                return false;
            }
        },
        get(key, defaultValue = null) {
            try {
                const item = localStorage.getItem(key);
                if (!item) return defaultValue;
                const data = JSON.parse(item);
                // 检查是否过期
                if (data.expires && Date.now() > data.expires) {
                    this.remove(key);
                    return defaultValue;
                };
                return data.value;
            } catch (error) {
                console.error('localStorage get error:', error);
                return defaultValue;
            }
        },
        remove(key) {
            try {
                localStorage.removeItem(key);
                return true;
            } catch (error) {
                console.error('localStorage remove error:', error);
                return false;
            }
        },
        update(key, newValue) {
            try {
                const item = localStorage.getItem(key);
                if (!item) return false;
                const data = JSON.parse(item);
                data.value = newValue;
                data.timestamp = Date.now();
                localStorage.setItem(key, JSON.stringify(data));
                return true;
            } catch (error) {
                console.error('localStorage update error:', error);
                return false;
            }
        },
        clear() {
            try {
                localStorage.clear();
                return true;
            } catch (error) {
                console.error('localStorage clear error:', error);
                return false;
            }
        },
        has(key) {
            try {
                const item = localStorage.getItem(key);
                if (!item) return false;
                const data = JSON.parse(item);
                if (data.expires && Date.now() > data.expires) {
                    this.remove(key);
                    return false;
                };
                return true;
            } catch (error) {
                console.error('localStorage has error:', error);
                return false;
            }
        },
        keys() {
            try {
                return Object.keys(localStorage);
            } catch (error) {
                console.error('localStorage keys error:', error);
                return false;
            }
        },
        getExpires(key) {
            try {
                const item = localStorage.getItem(key);
                if (!item) return null;
                const data = JSON.parse(item);
                if (!data.expires) return null;
                const remaining = data.expires - Date.now();
                return remaining > 0 ? remaining : 0;
            } catch (error) {
                console.error('localStorage getExpires error:', error);
                return null;
            }
        },
        getSize() {
            try {
                let total = 0;
                for (const key in localStorage) {
                    if (localStorage.hasOwnProperty(key)) {
                        const value = localStorage.getItem(key);
                        total += key.length + (value ? value.length : 0);
                    }
                };
                return total;
            } catch (error) {
                console.error('localStorage getSize error:', error);
                return 0;
            }
        }
    },
    loading: (title = "数据加载中，请稍后", bg = "rgba(0,0,0,0.4)", color = "#ffffff") => {
        const style = document.createElement("style");
        let styles = "dialog {width:100%;height:100%;background-color:transparent;padding:0;margin:0;outline:none;border:none;min-width:100%;min-height:100%;}";
        styles += "dialog::backdrop {background-color: " + bg + ";}";
        styles += ".loading,.loading>div {position:relative;box-sizing:border-box;}";
        styles += ".loading {display:block;font-size:0;color: " + color + ";position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);width:64px;height:64px;}";
        styles += ".loading::after {content:attr(data-loading-text);color: " + color + ";font-size:16px;display:block;white-space:nowrap;position:absolute;left:50%;top:calc(100% + 20px);transform:translateX(-50%)}";
        styles += ".loading>div {display:inline-block;float:none;background-color:currentColor;border:0 solid currentColor;position:absolute;top:50%;left:50%;width:13px;height:13px;margin-top:-4px;margin-left:-4px;border-radius:100%;animation:ball-spin-clockwise 1s infinite ease-in-out;}";
        styles += ".loading>div:nth-child(1) {top:5%;left:50%;animation-delay:-0.875s;}";
        styles += ".loading>div:nth-child(2) {top:18.1801948466%;left:81.8198051534%;animation-delay:-0.75s;}";
        styles += ".loading>div:nth-child(3) {top:50%;left:95%;animation-delay:-0.625s;}";
        styles += ".loading>div:nth-child(4) {top:81.8198051534%;left:81.8198051534%;animation-delay:-0.5s;}";
        styles += ".loading>div:nth-child(5) {top:94.9999999966%;left:50.0000000005%;animation-delay:-0.375s;}";
        styles += ".loading>div:nth-child(6) {top:81.8198046966%;left:18.1801949248%;animation-delay:-0.25s;}";
        styles += ".loading>div:nth-child(7) {top:49.9999750815%;left:5.0000051215%;animation-delay:-0.125s;}";
        styles += ".loading>div:nth-child(8) {top:18.179464974%;left:18.1803700518%;animation-delay:0s;}";
        styles += "@keyframes ball-spin-clockwise {0%,100%{opacity:1;transform:scale(1)}20% {opacity:1}80% {opacity:0;transform:scale(0)}}}";
        style.id = "loading_Style_0078125a1";
        style.innerHTML = styles;
        const dialog = document.createElement("dialog");
        dialog.id = "dialog_id_33068080ac127";
        const divLoading = document.createElement("div");
        divLoading.classList = "loading";
        divLoading.setAttribute("data-loading-text", title);
        const dom = document.createDocumentFragment();
        for (var i = 0; i < 8; i++) {
            let div = document.createElement("div");
            dom.appendChild(div);
        };
        divLoading.appendChild(dom);
        dialog.appendChild(divLoading);
        return {
            show: () => {
                if (!document.getElementById("loading_Style_0078125a1")) {
                    document.head.appendChild(style);
                };
                if (document.getElementById("dialog_id_33068080ac127")) return;
                document.body.appendChild(dialog);
                document.getElementById("dialog_id_33068080ac127").showModal();
            },
            hide: () => {
                document.getElementById("dialog_id_33068080ac127").close();
                setTimeout(() => {
                    if (document.getElementById("loading_Style_0078125a1")) {
                        document.getElementById("loading_Style_0078125a1").parentNode.removeChild(document.getElementById("loading_Style_0078125a1"));
                    };
                    if (document.getElementById("dialog_id_33068080ac127")) {
                        document.getElementById("dialog_id_33068080ac127").parentNode.removeChild(document.getElementById("dialog_id_33068080ac127"));
                    }
                }, 300);
            }
        }
    },
    setTheme: (themeName) => {
        if(themeName === "default") document.documentElement.removeAttribute("data-theme");
        document.documentElement.setAttribute('data-theme', themeName);
        $.storage.set("wang_theme", themeName);
    },
    baseUrl: `${window.location.protocol}//${window.location.hostname}:5320`
};
function initialize(container = "body", obj = {}) {
    const config = {
        showLoading: obj.showLoading ?? false,
        message: obj.message ?? "正在加载页面，请稍后",
        bg: obj.bg ?? "rgba(255, 255, 255, 0.6)",
        color: obj.color ?? "#333333"
    };

    // 初始化加载状态
    let loadingDialog = null;
    const showLoading = () => {
        if (config.showLoading) {
            loadingDialog = $.loading(config.message, config.bg, config.color);
            document.documentElement.style.overflow = "hidden";
            loadingDialog.show();
        }
    };

    // 关闭加载状态
    const hideLoading = () => {
        if (config.showLoading && loadingDialog) {
            document.documentElement.style.removeProperty("overflow");
            if (!document.documentElement.style.cssText) {
                document.documentElement.removeAttribute("style");
            }
            loadingDialog.hide();
        }
    };

    // 设置元素可见
    const setElementVisible = (element) => {
        if (element) element.style.opacity = "1";
    };

    // 获取主题
    const fetchTheme = async () => {
        try {
            const response = await fetch(`${window.location.protocol}//${window.location.hostname}:5320/api/theme/active`);
            if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
            const data = await response.json();
            return data.data.THEME_CODE;
        } catch (error) {
            console.error("Failed to fetch theme:", error);
            return null;
        }
    };

    return new Promise(async (resolve, reject) => {
        try {
            showLoading();
            const element = document.querySelector(container || "body");
            if (!element) throw new Error(`选择器中找不到元素：${container || "body"}`);

            // 获取远程主题
            const remoteTheme = await fetchTheme();
            if (!remoteTheme) throw new Error("无法获取主题");

            $.setTheme(remoteTheme);

            setElementVisible(element);
            hideLoading();
            resolve();
        } catch (error) {
            hideLoading();
            reject(error);
        }
    });
}